<?php
using("Db_Adodb_Service");

class Tests_Db_Adodb_Service extends UnitTestCase {
	
	/**
	 * Database service
	 *
	 * @var Db_Adodb_Service
	 */
	private $_dsn = "mysql://Catch22:divein@localhost/test";
	
	private $_dsn2 = "mysql://Catch22:divein@localhost/foo";
	
	private $_query = "INSERT INTO CustomAttributes (`key`, `value`) VALUES ('foo', 'bar')";
	
//	public function testConstruct() {
//		try {
//			$dbh = new Db_Adodb_Service($this->_dsn2);
//			$this->fail();
//		} catch (Db_Common_SqlException $e) {
//			$this->pass();
//		}
//	}

	// Bugbug Note that the last insert persists longer than the dbh object
	public function testInsertId() {
		$dbh = new Db_Adodb_Service($this->_dsn);
		$this->assertTrue($dbh->lastInsertId() == 0);
		$dbh->save($this->_query);
		$this->assertTrue($dbh->lastInsertId() > 0);
	}
	
	public function testSave() {
		$dbh = new Db_Adodb_Service($this->_dsn);
		$this->assertTrue($dbh->save($this->_query));
		try {
			$query = "INSERT INTO CustomAttributes (key, value) VALUES (?, ?)";
			$dbh->save($query);
			$this->fail();
		} catch (Db_Common_SqlException $e) {
			$this->pass();
		}
		$query = "UPDATE CustomAttributes SET `key` = 'foo' WHERE id = " . $dbh->lastInsertId();
		$this->assertTrue($dbh->save($query));
	}
	
	public function testSelect() {
		$dbh = new Db_Adodb_Service($this->_dsn);
		$query = "SELECT * FROM CustomAttributes";
		$results = $dbh->select($query);
		$this->assertTrue(is_a($results, "Db_Common_ResultSet"));
		$this->assertTrue(is_a($results, "Db_Adodb_ResultSet"));

		try {
			$query = "SELECT * FROM CustomAttributes WHERE foo = ?";
			$dbh->select($query);
			$this->fail();
		} catch (Db_Common_SqlException $e) {
			$this->pass();
		}
	}
	
	public function testUpdate() {
		$dbh = new Db_Adodb_Service($this->_dsn);
		$this->assertTrue($dbh->affectedRows() == 0);
		$query = "UPDATE CustomAttributes SET `key` = 'bar' WHERE id = " . $dbh->lastInsertId();
		$dbh->save($query);
		$this->assertTrue($dbh->affectedRows() > 0);
	}
	
	public function testTransaction() {
		$ado = & ADONewConnection($this->_dsn);
		$lastInsertId = $ado->Insert_ID();
		$ado->StartTrans();
		$ado->Execute($this->_query);
		$this->assertFalse($lastInsertId == $ado->Insert_ID());
		$ado->CompleteTrans();
	}
	
//	public function testTransaction() {
//		$dbh = new Db_Adodb_Service($this->_dsn);
//		$lastInsertId = $dbh->lastInsertId();
//		$this->assertTrue($dbh->startTransaction());
//		$dbh->save($this->_query);
//		$this->assertTrue($lastInsertId == $dbh->lastInsertId);
//		$this->assertTrue($dbh->stopTransaction());
//	}

}
?>